<template>
    <div>
        <a-form layout="inline"
                :model="searchData"
                style="margin: 10px 0">
            <a-form-item>
                <a-input v-model:value="searchData.title" placeholder="标题"></a-input>
            </a-form-item>
            <a-form-item>
                <a-select
                        ref="select"
                        v-model:value="searchData.goodsId"
                        placeholder="商品"
                        style="width: 120px"
                        :options="goodsList"
                        :field-names="{label:'name',value:'id'}"
                ></a-select>
            </a-form-item>
            <a-form-item>
                <a-button type="primary" @click="load">搜索</a-button>
            </a-form-item>
            <a-form-item>
                <a-button type="default" @click="rest">重置</a-button>
            </a-form-item>
        </a-form>
        <a-button type="primary" style="margin-bottom: 10px" @click="openModal({})">新增</a-button>
        <a-table :dataSource="salesBillList"
                 :columns="columns"
                 :pagination="pagination"
                 @change="handlerChange"
                 bordered>
            <template #user="{text,record}">
                {{beLongUser(text)}}
            </template>
            <template #goods="{text,record}">
                {{beLongGoods(text)}}
            </template>
            <template #state="{text,record}">
                <a-tag v-if="text == 0" color="default">
                    <template #icon>
                        <clock-circle-outlined/>
                    </template>
                    等待物料员打包
                </a-tag>
                <a-tag v-if="text == 1" color="processing">
                    <template #icon>
                        <sync-outlined :spin="true"/>
                    </template>
                    等待出库
                </a-tag>
                <a-tag v-if="text == 2" color="success">
                    <template #icon>
                        <check-circle-outlined/>
                    </template>
                    出库成功
                </a-tag>
            </template>
            <template v-slot:action="{text,record}">
                <a-space>
                    <a-button type="primary" v-if="record.state == 0" @click="openModal(record)">编辑</a-button>
                    <a-popconfirm
                            title="删除数据无法恢复，请确认是否删除？"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="okDelete(record.id)"
                    >
                        <a-button v-if="record.state != 1" type="danger">删除</a-button>
                    </a-popconfirm>
                </a-space>
            </template>
        </a-table>
        <a-drawer
                title="出库申请单"
                :width="1000"
                :visible="visible"
                :body-style="{ paddingBottom: '40px' }"
                :footer-style="{ textAlign: 'right' }"
                @close="onClose"
        >
            <a-form layout="vertical" :model="salesBill">
                <a-row :gutter="16">
                    <a-col :span="24">
                        <a-form-item
                                v-bind="validateInfos.title"
                                label="标题"
                                name="title">
                            <a-input v-model:value="salesBill.title"/>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item
                                v-bind="validateInfos.goodsId"
                                label="出库商品"
                                name="goodsId">
                            <a-select
                                    ref="select"
                                    v-model:value="salesBill.goodsId"
                                    placeholder="请选择"
                                    @change="handlerSelected"
                            >
                                <a-select-option v-for="(item,index) in goodsList"
                                                 :disabled="item.quantity < 1"
                                                 :key="index"
                                                 :value="item.id">
                                    {{item.name}}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item
                                v-bind="validateInfos.quantity"
                                label="出库数量"
                                name="quantity">
                            <a-input-number v-model:value="salesBill.quantity"
                                            :disabled="salesBill.goodsId == ''"
                                            :min="1"
                                            :max="maxNum"/>
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row :gutter="16">
                    <a-col :span="24">
                        <a-form-item
                                v-bind="validateInfos.remark"
                                label="出库详情"
                                name="remark">
                            <a-textarea :auto-size="{minRows:3}" v-model:value="salesBill.remark"/>
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row :gutter="16">
                    <a-col :span="24">
                        <a-form-item>
                            <a-space>
                                <a-button type="primary" @click="submitOk">
                                    提交
                                </a-button>
                                <a-button type="default" @click="resetFields">
                                    重置
                                </a-button>
                            </a-space>

                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-drawer>
    </div>
</template>

<script>
    import {ref, onMounted} from 'vue'
    import axios from 'axios'
    import {message, Form} from 'ant-design-vue';
    import {SyncOutlined, ClockCircleOutlined, CheckCircleOutlined} from '@ant-design/icons-vue'
    import {SessionStorage} from "../../../public/session-storage";

    export default {
        name: "sales-salesBill",
        components: {
            SyncOutlined,
            ClockCircleOutlined,
            CheckCircleOutlined
        },
        setup() {
            const columns = [
                {
                    title: 'ID',
                    dataIndex: 'id',
                    key: 'id',
                    align: 'center'
                },
                {
                    title: '标题',
                    dataIndex: 'title',
                    key: 'title',
                    align: 'center'
                },
                {
                    title: '商品',
                    dataIndex: 'goodsId',
                    key: 'goodsId',
                    slots: {customRender: 'goods'},
                    align: 'center'
                },
                {
                    title: '数量',
                    dataIndex: 'quantity',
                    key: 'quantity',
                    align: 'center'
                },
                {
                    title: '描述',
                    dataIndex: 'remark',
                    key: 'remark',
                    align: 'center'
                },
                {
                    title: '创建人',
                    dataIndex: 'userId',
                    key: 'userId',
                    slots: {customRender: 'user'},
                    align: 'center'
                },
                {
                    title: '状态',
                    dataIndex: 'state',
                    key: 'state',
                    slots: {customRender: 'state'},
                    align: 'center'
                },
                {
                    title: '操作',
                    key: 'action',
                    slots: {customRender: 'action'},
                    align: 'center'
                }
            ]

            const salesBill = ref({
                title: '',
                goodsId: '',
                quantity: '',
                remark: '',
            })
            const useForm = Form.useForm
            const loginUser = ref({})
            const salesBillList = ref()
            const userList = ref([])
            const goodsList = ref([])
            const searchData = ref({})
            const maxNum = ref(1)
            const pagination = ref({
                current: 1,
                pageSize: 6,
            })
            const {validate, validateInfos, resetFields} = useForm(salesBill, {
                title: [{required: true, message: '标题不能为空', trigger: ['submit', 'change']}],
                goodsId: [{required: true, message: '请选择商品', trigger: ['submit', 'change']}],
                quantity: [{required: true, message: '请输入商品数量', trigger: ['submit', 'change']}],
                remark: [{required: true, message: '销售详情不能为空', trigger: ['submit', 'change']}],
            })

            const visible = ref(false);

            const load = () => {
                axios.get('/salesBill/list', {
                    params: {
                        pageNum: pagination.value.current,
                        pageSize: pagination.value.pageSize,
                        title: searchData.value.title,
                        goodsId: searchData.value.goodsId,
                    }
                }).then(rs => {
                    console.log("查找结果：", rs)
                    salesBillList.value = rs.data.data.list
                    pagination.value.total = rs.data.data.total
                })
            }

            const rest = () => {
                searchData.value = {}
                load()
            }

            const handlerChange = (pageInfo) => {
                pagination.value = pageInfo
                load()
            }

            const openModal = (obj) => {
                console.log("模态框参数：", obj)
                visible.value = true;
                if (JSON.stringify(obj) == '{}') {
                    resetFields()
                } else {
                    salesBill.value = JSON.parse(JSON.stringify(obj))
                }
            }

            const submitOk = () => {
                console.log("提交")
                validate().then(() => {
                    salesBill.value.userId = loginUser.value.id
                    salesBill.value.state = 0

                    axios.post('/salesBill/saveOrUpdate', salesBill.value).then(rs => {
                        console.log("新增或修改结果：", rs)
                        if (rs.data.code == 200) {
                            onClose()
                            message.success("操作成功")
                            load()
                        } else {
                            message.error(rs.data.message)
                        }
                    })
                }).catch(() => {
                    console.log("校验失败")
                })
            }

            const onClose = () => {
                // leaveVisible.value = false
                visible.value = false
            }

            const handlerSelected = (value) => {
                goodsList.value.forEach(val => {
                    if (val.id == value) {
                        maxNum.value = val.quantity
                        return
                    }
                })
            }

            const okDelete = (id) => {
                console.log("要删除的ID：" + id)
                axios.delete('/salesBill/delete/' + id).then(rs => {
                    if (rs.data.code == 200) {
                        message.success("删除成功")
                        load()
                    } else {
                        message.error(rs.data.message)
                    }
                })
            }

            const beLongUser = (userId) => {
                let rs = ''
                userList.value.forEach(val => {
                    if (val.id == userId) {
                        rs = val.username
                        return rs
                    }
                })
                return rs == '' ? userId : rs
            }
            const beLongGoods = (goodsId) => {
                let rs = ''
                goodsList.value.forEach(val => {
                    if (val.id == goodsId) {
                        rs = val.name
                        return rs
                    }
                })
                return rs == '' ? goodsId : rs
            }

            onMounted(() => {
                loginUser.value = SessionStorage.get('loginUser')
                axios.get('/user/queryAll').then(rs => {
                    userList.value = rs.data.data
                })
                axios.get('/goods/queryAll').then(rs => {
                    goodsList.value = rs.data.data
                })
                load()
            })
            return {
                columns,
                pagination,
                handlerChange,
                searchData,
                load,
                rest,
                openModal,
                visible,
                okDelete,
                salesBill,
                salesBillList,
                goodsList,
                submitOk,
                handlerSelected,
                validateInfos,
                resetFields,
                maxNum,
                onClose,
                beLongUser,
                beLongGoods
            }
        }
    }
</script>

<style scoped>

</style>